<template>
<!-- <el-dialog title="员工分配"  width="60vw" height="60vh" top="5vh" append-to-body :close-on-click-modal="false" :visible.sync="visible" v-if="visible"   @close="callback">
   </el-dialog> -->
   <div>
  <div style="height: 75vh;">
    <div style="height:70vh; ">
      <div class="mb10">
        <!-- <el-switch v-model="value" active-text="公式" inactive-text="人工" @change="switchChange"></el-switch> -->
      </div>
      <div class="h50 mb10">
        <!--        <div class="fl " v-for="(item,index) in sourceData" :key="index">-->
        <!--          <span class="w200 blue fontweight">{{ item.jjxName }}</span>-->
        <!--          <span class="ml30">可分配余额：<span class="font22 blue">{{ $formatNum(calculationMap[item.jjxId].jje) }}</span>元</span>-->
        <!--          <span class="ml30">已分配金额：<span class="font22 blue">{{ $formatNum(calculationMap[item.jjxId].sye) }}</span>元</span>-->
        <!--          <span class="ml30">剩余可分配额：<span class="font22 blue">{{ $formatNum(calculationMap[item.jjxId].jje - calculationMap[item.jjxId].sye) }}元</span></span>-->
        <!--        </div>-->
        <el-row :gutter="20">
          <el-col v-for="(item,index) in sourceData" :key="index" :span="12">
            <div class="ffdi juzhong mb5">
              <span class=" blue fontweight">{{ item.jjxName }}</span>
              <span class="ml30">余额：<span class="font22 blue">{{ $formatNum(calculationMap[item.jjxId].jje - calculationMap[item.jjxId].sye) }}元</span></span>
              <el-tooltip placement="top" effect="light" width="1000">
                <div slot="content">
                  <span>可分配余额：<span class="font22 blue">{{ $formatNum(calculationMap[item.jjxId].jje) }}</span>元</span>
                  <span class="ml30">已分配金额：<span class="font22 blue">{{ $formatNum(calculationMap[item.jjxId].sye) }}</span>元</span>
                  <div style="display:none">{{ksye=calculationMap[item.jjxId].sye}}</div>
                  <span class="ml30">剩余可分配额：<span class="font22 blue">{{ $formatNum(calculationMap[item.jjxId].jje - calculationMap[item.jjxId].sye) }}</span>元</span>
                </div>
                <div style="width:40px; float:right;">
                  <i class="el-icon-warning"></i>
                </div>
              </el-tooltip>
            </div>
          </el-col>
        </el-row>

      </div>
      <el-table ref="bmxqTable" :data="tableResult" height="80%" width="100%" border>
        <el-table-column type="index" width="70" label="序号" header-align="center" align="center"></el-table-column>
        <el-table-column prop="deptName" label="机构名称" min-width="270" header-align="center"  align="center"></el-table-column>
        <el-table-column prop="jjPnum" label="机构人数" min-width="100" header-align="center"  align="center"></el-table-column>
        <el-table-column prop="jjPavg" label="人均奖金" min-width="100"  header-align="center"  align="right"></el-table-column>
        <!--<el-table-column prop="jjZey" label="奖金总额l" width="100"></el-table-column>-->
        <el-table-column prop="jjZey" label="奖金总额(元)" :formatter="totalAmountN" min-width="100" header-align="center" align="right"></el-table-column>
        <!--循环体-->
        <el-table-column v-for="(item,index) in tableJjxMc" :key="index" :label="item" min-width="150" header-align="center">

          <el-table-column :prop="item" label="金额(元)" min-width="100" header-align="center" align="right">
            <template slot-scope="scope">
              <!-- <span v-if="tableResult[scope.$index][item] != null">
                <span  v-if="!value" v-show="false">{{ $formatNum(tableResult[scope.$index][item]["jjJe"]) }}</span>
                <el-input-number v-if="!value" v-model="tableResult[scope.$index][item].jjJe" :precision="2" :step="1" :min="0"
                                 :max="1000000000" style="width:90%"
                                 @change="lbChangeN(tableResult[scope.$index][item].jjJe,item,scope.$index)"></el-input-number>
                <span v-else>{{ $formatNum(tableResult[scope.$index][item]["jjJe"]) }}</span>
              </span> -->
              <span>{{scope.row[item+'value']}}</span>
            </template>
          </el-table-column>

          <el-table-column :prop="item+'备注'" label="备注" min-width="150" header-align="center">
            <template slot-scope="scope">
              <span v-if="tableResult[scope.$index][item+'备注'] != null">
                <span v-if="tableResult[scope.$index][item+'备注'].jjJe != tableResult[scope.$index][item+'备注'].jjYsje" v-show="false">{{ tableResult[scope.$index][item+'备注']["jjBz"] }}</span>
                <el-input v-if="tableResult[scope.$index][item+'备注'].jjJe != tableResult[scope.$index][item+'备注'].jjYsje"
                          v-model="tableResult[scope.$index][item+'备注'].jjBz" placeholder="请输入修改备注" style="width:90%"></el-input>
                <span v-else>{{ tableResult[scope.$index][item+'备注']["jjBz"] }}</span>
              </span>
            </template>
          </el-table-column>

        </el-table-column>
      </el-table>

      <!--      请不要删除吖~_~     -->
<!--      <el-table :data="dataList" :span-method="objectSpanMethod" border height="80%" width="100%">-->
<!--        <el-table-column type="index" width="80" label="序号" align="center"></el-table-column>-->
<!--        <el-table-column prop="deptName" label="机构名称" header-align="center" min-width="260px"></el-table-column>-->
<!--        <el-table-column prop="deptId" label="奖金总额(元)" header-align="center" align="right" min-width="150px">-->
<!--          <template slot-scope="scope">-->
<!--            {{ $formatNum(totalAmount(scope.row.deptId)) }}-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column prop="jjxMc" label="奖金项名称" align="center" min-width="150px"></el-table-column>-->
<!--        <el-table-column prop="jjJe" label="奖金项金额（元）" header-align="center" align="right" min-width="150px">-->
<!--          <template slot-scope="scope">-->
<!--            <el-input-number v-if="!value" v-model="dataList[scope.$index].jjJe" :precision="2" :step="1" :min="0"-->
<!--                             :max="1000000000" style="width:90%"-->
<!--                             @change="lbChange(scope.row.jjJe,scope.$index)"></el-input-number>-->
<!--            <span v-else>{{ $formatNum(dataList[scope.$index].jjJe) }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column prop="jjBz" label="备注信息" header-align="center" min-width="150px">-->
<!--          <template slot-scope="scope">-->
<!--            <el-input v-if="dataList[scope.$index].jjJe != dataList[scope.$index].jjYsje"-->
<!--                      v-model="dataList[scope.$index].jjBz" placeholder="请输入修改备注" style="width:90%"></el-input>-->
<!--            <span v-else>{{ dataList[scope.$index].jjBz }}</span>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--      </el-table>-->
      <!--      请不要删除吖~_~     -->

      <!-- <el-button type="primary" plain @click="saveBmList()" class="fr mt10 ml10">保存结果</el-button>
      <el-button type="primary" @click="pageSwitch()" class="fr mt10">重新配置</el-button>
      <el-button class="fr mt10 ml10" @click="btnExportJg">导出数据</el-button> -->
    </div>
    <!--选择机构分组-->
    <jiangjinJgxxFzxx ref="jiangjinJgxxFzxx" @getChildValue="setJgfzStr"></jiangjinJgxxFzxx>
  </div>
  <span slot="footer" class="dialog-footer" style="text-align:center;display: block">
            <el-button @click="btnExportJg">导出数据</el-button>
            <el-button type="primary" @click="saveBmList()">保存</el-button>
            <!-- <el-button @click="quanPing">全屏</el-button> -->
            <!-- <el-button @click="callback">取 消</el-button> -->
        </span>
 </div>    
</template>

<script>
import {getObj, putObj, updateBm} from '@/api/jiangjin/jiangjinfpjjfpdjb'
import {saveBmList, getBmfpList} from '@/api/jiangjin/jiangjinfpjjbmfppzmxb'
import {getJjDeptJjx} from '@/api/jiangjin/jiangjinjjxxxb'
import {getJjDeptJjgtoPrant} from '@/api/admin/sysformula'
import jiangjinJgxxFzxx from './jiangjin-jgxx-fzxx'
import {getJjListByDeptId, getJjListByDeptIdFzMx} from "@/api/jiangjin/jiangjinjjjgwh";
import XLSX from "xlsx";
import FileSaver from 'file-saver'

export default {
  components: {
    jiangjinJgxxFzxx
  },
  data() {
    return {
      tablebz: false,
      drawer: false,
      direction: 'btt',
      jjye: 0,//奖金余额
      pzHjs: 0,//配置合计数
      lbHjs: 0,//列表合计数
      activeClass: 0,//滚动条属性
      value: true,//人工、公式
      cutPage: true,
      dataList: [],
      fpData: {},//分配信息
      deptId: '',
      deptName: '',

      gsData: [], //公式List
      //奖金项
      jjxOptions: [],
      //数据配置源主
      sourceData: [],
      //数据配置源主金额
      sourceMap: {},
      //计算后主金额
      calculationMap: {},
      //数据配置源子
      sourceDataSub: {},
      //主index
      sourceDataIndex: -1,
      //奖项统计list
      fpsjList: [],
      //奖项统计动态列list
      lieList: [],
      //单元格定位信息list
      dygList: [],
      fzMx: [],
      //横板显示记录
      tableResult:[],
      //横板显示所有奖金项
      tableJjxMc:[],
      visible:false,
      ksye:0
    }
  },
  methods: {
      callback(){
          this.visible=false
          this.$emit('guan','关闭')
      },
      quanPing(){
        this.$emit('guan','全屏')
      },
    getActiveClass(index) {
      this.activeClass = index
      let jump = document.querySelectorAll('.condition-container-bm')
      jump[index].scrollIntoView({block: 'start', behavior: 'auto'})
    },
    //滚动条监听
    scrollEvent(e) {
      let scrollItems = document.querySelectorAll('.condition-container-bm')
      for (let i = scrollItems.length - 1; i >= 0; i--) {
        // 判断滚动条滚动距离是否大于当前滚动项可滚动距离
        let judge = e.target.scrollTop >= scrollItems[i].offsetTop - scrollItems[0].offsetTop
        if (judge) {
          this.activeClass = i
          break
        }
      }
      // 滚动条触底了
      if (e.srcElement.scrollTop + e.srcElement.offsetHeight === e.srcElement.scrollHeight) {
        this.activeClass = scrollItems.length - 1
      }
    },
    //list合计金额计算(新)
    totalAmountN(row, column, cellValue, index){
      const deptId = row.deptId;

      let je = 0;
      for (var a = 0; a < this.dataList.length; a++) {
        if (this.dataList[a].deptId == deptId) {
          je = je + this.dataList[a].jjJe
        }
      }

      return this.$formatNum(je.toFixed(2));
    },
    //list合计金额计算
    totalAmount(deptId) {
      var je = 0;
      for (var a = 0; a < this.dataList.length; a++) {
        if (this.dataList[a].deptId == deptId) {
          je = je + this.dataList[a].jjJe
        }
      }

      return je.toFixed(2);
    },
    //列合并
    objectSpanMethod({row, column, rowIndex, columnIndex}) {
      if (columnIndex === 1 || columnIndex === 2) {
        if (rowIndex > 0 && this.dataList[rowIndex].deptName == this.dataList[rowIndex - 1].deptName) {
          return {
            rowspan: 0,
            colspan: 0
          }
        } else {
          var j = 0;
          for (var i = rowIndex; i < this.dataList.length; i++) {
            if (this.dataList[rowIndex].deptName == this.dataList[i].deptName) {
              j++;
            } else {
              break;
            }
          }
          return {
            rowspan: j,
            colspan: 1
          }
        }
      }
    },
    getJjxXq() {
      //1.主取得
      this.sourceData = JSON.parse(this.fpData.jjxXq);
      this.sourceMap = JSON.parse(this.fpData.jjxJeXq);

      //2.生成子(有记录需要在这里处理)
      if (this.fpData.bmGs == null) {
        for (let i = 0; i < this.sourceData.length; i++) {
          this.$set(this.sourceDataSub, this.sourceData[i]["jjxId"], []);
        }
      } else {
        this.sourceDataSub = JSON.parse(this.fpData.bmGs);
      }

      this.pzChange();
    },
    switchChange(val) {
      if (val) {
        this.$confirm('执行后将还原成公式内容，是否执行！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.dataFormSubmit();
        }).catch(() => {
          this.value = false;
        })
      }
    },
    //公式配置已分配金额计算
    pzChange() {
      var zhjs = 0;
      for (var a in this.sourceData) {
        var hjs = 0;
        for (var b in this.sourceDataSub[this.sourceData[a].jjxId]) {
          for (var c in this.sourceDataSub[this.sourceData[a].jjxId][b].jjConfig) {
            hjs = hjs + (this.sourceDataSub[this.sourceData[a].jjxId][b].jjConfig[c].jjJe == undefined ? 0 : this.sourceDataSub[this.sourceData[a].jjxId][b].jjConfig[c].jjJe);
          }
        }

        this.sourceMap[this.sourceData[a].jjxId].jjYe = parseFloat((this.sourceMap[this.sourceData[a].jjxId].jjZe - this.sourceMap[this.sourceData[a].jjxId].ygJj - this.sourceMap[this.sourceData[a].jjxId].dxFp - hjs.toFixed(2)).toFixed(2));
        this.sourceMap[this.sourceData[a].jjxId].bmJj = parseFloat(hjs.toFixed(2));

        zhjs = zhjs + hjs;
      }

      this.pzHjs = zhjs.toFixed(2);
    },
    pzChanges(j) {
      let d = 0;
      for (var i in j.fzInfo) {
        if (j.fzInfo[i].jjJe) {
          d += j.fzInfo[i].jjJe;
        }
      }
      this.$set(j, "jjJe", d);
      this.pzChange();
    },
    //计算后数据加工
    dataProcessing() {
      this.calculationMap = {};
      //数据合成
      for (var a in this.sourceData) {
        this.$set(this.calculationMap, this.sourceData[a]["jjxId"], {
          jje: (this.sourceMap[this.sourceData[a]["jjxId"]].jjZe - this.sourceMap[this.sourceData[a]["jjxId"]].ygJj - this.sourceMap[this.sourceData[a]["jjxId"]].dxFp).toFixed(2),
          sye: 0,
          yjs: 0
        });
      }

      this.lbChange();
    },
    //list列表已分配金额计算
    lbChangeN(val,item,index){
      ////console.log(val);
      ////console.log(item);

      if (val == undefined) {
        // this.$nextTick(()=>{
          this.tableResult[index][item].jjJe = 0;
        // })
      }

      for (var a in this.dataList) {
        this.calculationMap[this.dataList[a].jjzxId].yjs = this.calculationMap[this.dataList[a].jjzxId].yjs + this.dataList[a].jjJe;
      }

      for (var a in this.sourceData) {
        this.calculationMap[this.sourceData[a]["jjxId"]].sye = this.calculationMap[this.sourceData[a]["jjxId"]].yjs;
        this.calculationMap[this.sourceData[a]["jjxId"]].yjs = 0;
      }
    },
    //list列表已分配金额计算
    lbChange(val, index) {
      if (index != undefined && val == undefined) {
        this.dataList[index].jjJe = 0;
      }

      // var hjs = 0;
      // for (var a in this.dataList) {
      //   hjs = hjs + this.dataList[a].jjJe
      // }
      // this.lbHjs = hjs.toFixed(2);

      for (var a in this.dataList) {
        this.calculationMap[this.dataList[a].jjzxId].yjs = this.calculationMap[this.dataList[a].jjzxId].yjs + this.dataList[a].jjJe;
      }

      for (var a in this.sourceData) {
        this.calculationMap[this.sourceData[a]["jjxId"]].sye = this.calculationMap[this.sourceData[a]["jjxId"]].yjs;
        this.calculationMap[this.sourceData[a]["jjxId"]].yjs = 0;
      }
    },
    csh() {
      this.jjye = 0;//奖金余额
      this.pzHjs = 0;//配置合计数
      this.lbHjs = 0;//列表合计数
      this.activeClass = 0;//滚动条属性
      this.gsData = [];
      this.jjxOptions = [];
      this.sourceData = [];
      this.sourceMap = {};
      this.sourceDataSub = {};
      this.dataList = [];
      this.fpData = {};
    },
    //横板记录显示用（奖金总额计算）
    setDataListJjZeY(){
      let je = 0;
      for(let i=0;i<this.dataList.length;i++){
        je = 0;
        for(let j=0;j<this.dataList.length;j++){
          if(this.dataList[j].deptId == this.dataList[i].deptId){
            je += this.dataList[j].jjJe;
          }
        }
        this.$set(this.dataList[i],"jjZey",je.toFixed(2));
      }
    },
    init(id) {
      this.csh();
      this.visible=true
      this.$nextTick(() => {
        // alert(id) 
        getObj(id).then(response => {

          this.fpData = response.data.data;
          this.$forceUpdate()
          getJjListByDeptIdFzMx(this.fpData.jjDeptId).then(res => {
            this.fzMx = res.data.data;
          })
          this.jjye = this.fpData.jjZe - this.fpData.ygJj - this.fpData.dxFp;

          if (this.fpData.bmFpfs == "人工") {
            this.value = false;
          } else {
            this.value = true;
          }

          this.deptId = this.fpData.jjDeptId;
          this.deptName = this.fpData.jjDeptName;
          this.getGsListOption();
          this.getJjxXq();

          getBmfpList(this.fpData.id).then(response => {
            this.dataList = response.data.data;
            this.dataProcessing();

            this.setDataListJjZeY();
            this.setDataColumns();


          })
        })
      })
    },
    //页面切换
    pageSwitch() {
      this.cutPage = true;
    },
    getSelectJg() {
      let lResult = [];
      const lId = this.sourceData[this.sourceDataIndex].jjxId;

      if (this.sourceDataSub[lId] !== undefined) {
        for (let i = 0; i < this.sourceDataSub[lId].length; i++) {
          lResult.push(this.sourceDataSub[lId][i].fzId);
        }
      }

      return lResult.join(',');
    },
    //选择分组
    openSelectFz(index1) {
      this.sourceDataIndex = -1;
      this.sourceDataIndex = index1;
      this.jgfzszVisible = true

      this.$nextTick(() => {
        this.$refs.jiangjinJgxxFzxx.init(this.deptId, this.getSelectJg());
      })
    },
    //设置
    setJgfzStr(obj) {
      let lId = 0;
      let sStr = [];

      let zs = 0;
      for (var i in obj) {
        zs += obj[i].ysNumber;
      }

      lId = this.sourceData[this.sourceDataIndex].jjxId;
      sStr = Object.keys(this.sourceDataSub);

      for (let i = 0; i < sStr.length; i++) {
        if (sStr[i] == lId) {
          for (let j = 0; j < obj.length; j++) {
            // obj[j].id  obj[j].jgFzName

            let fzInfo = [];
            for (var x in this.fzMx) {
              if (this.fzMx[x].fzId == obj[j].id) {
                fzInfo.push({
                  deptCode: this.fzMx[x].jgDeptCode,
                  deptName: this.fzMx[x].jgDeptName,
                  jjJe: zs
                })
              }
            }

            this.sourceDataSub[sStr[i]].push({
              fzId: obj[j].id,
              fzName: obj[j].jgFzName,
              jjWs: "1",
              jjConfig: [{
                gsId: '',
                gsName: "",
                jjJe: obj[j].ysNumber,
                jjxId: lId,
                jjxName: this.getJJxName(lId),
                jjxDate: this.getJJxDate(lId),
                fzInfo: fzInfo,
                errMsg: ''
              }]
            })
          }
          break;
        }
      }
      this.pzChange();
    },
    //取得公式数组
    getGsListOption() {
      //取得公式数组
      getJjDeptJjgtoPrant({id: this.deptId, getJJxNamegsType: '奖金算法', gsFl: '部门'}).then(res => {
        this.gsData = res.data.data;
      })

      //取得奖金项
      getJjDeptJjx(this.deptId).then(res => {
        const xData = res.data.data;
        this.jjxOptions = [];
        this.jjxOptions = xData;
      })
    },
    //自定义表头合计金额 20211005新增
    selBthj(fzName) {
      var je = 0;

      for (var a in this.sourceData) {//奖金项循环
        for (var b in this.sourceDataSub[this.sourceData[a].jjxId]) {//分组循环
          if (this.sourceDataSub[this.sourceData[a].jjxId][b].fzName == fzName) {
            for (var c in this.sourceDataSub[this.sourceData[a].jjxId][b].jjConfig) {//拆分奖金项循环
              je = je + this.sourceDataSub[this.sourceData[a].jjxId][b].jjConfig[c].jjJe;
            }
          }
        }
      }

      return je;
    },
    //表字段金额合计 20211005新增
    selJjhj(zjjxId, jjxId, fzName) {
      var je = 0;

      for (var a in this.sourceDataSub[zjjxId]) {//分组循环
        if (this.sourceDataSub[zjjxId][a].fzName == fzName) {
          for (var b in this.sourceDataSub[zjjxId][a].jjConfig) {//拆分奖金项循环
            if (this.sourceDataSub[zjjxId][a].jjConfig[b].jjxId == jjxId) {
              je = je + this.sourceDataSub[zjjxId][a].jjConfig[b].jjJe;
            }
          }
        }
      }
      return je;
    },
    //拆分奖金项明细查询 20211005新增
    selJjxMx(zjjxId, jjxId, fzName) {
      this.dygList = [];
      var xb = 0;

      for (var a in this.sourceDataSub[zjjxId]) {//分组循环
        if (this.sourceDataSub[zjjxId][a].fzName == fzName) {
          for (var b in this.sourceDataSub[zjjxId][a].jjConfig) {//拆分奖金项循环
            if (this.sourceDataSub[zjjxId][a].jjConfig[b].jjxId == jjxId) {
              this.dygList[xb] = this.sourceDataSub[zjjxId][a].jjConfig[b];
              xb = xb + 1;
            }
          }
        }
      }
    },
    //分配情况信息表合并列 20211005新增
    fpqkSpanMethod({row, column, rowIndex, columnIndex}) {
      if (columnIndex === 1) {
        if (rowIndex > 0 && this.fpsjList[rowIndex].zjjxId == this.fpsjList[rowIndex - 1].zjjxId) {
          return {
            rowspan: 0,
            colspan: 0
          }
        } else {
          var j = 0;
          for (var i = rowIndex; i < this.fpsjList.length; i++) {
            if (this.fpsjList[rowIndex].zjjxId == this.fpsjList[i].zjjxId) {
              j++;
            } else {
              break;
            }
          }
          return {
            rowspan: j,
            colspan: 1
          }
        }
      }
    },
    handleClose(done) {
      this.tablebz = false;
      done();
    },
    close() {
      this.tablebz = false;
      this.drawer = false;
    },
    //分配数据格式处理 20211006新增
    distributionData() {
      this.fpsjList = [];
      this.lieList = [];
      //定义list和动态列名
      var fpsjList = new Map();
      var lieList = new Map();

      for (var a in this.sourceData) {//奖金项循环
        for (var b in this.sourceDataSub[this.sourceData[a].jjxId]) {//分组循环
          //插入分组map（有直接逃过）
          if (!lieList.has(this.sourceDataSub[this.sourceData[a].jjxId][b].fzId)) {
            lieList.set(this.sourceDataSub[this.sourceData[a].jjxId][b].fzId, this.sourceDataSub[this.sourceData[a].jjxId][b].fzName);
          }

          for (var c in this.sourceDataSub[this.sourceData[a].jjxId][b].jjConfig) {//拆分奖金项循环
            //插入拆分奖金map（有直接逃过）
            if (!fpsjList.has(this.sourceData[a].jjxId + "-" + this.sourceDataSub[this.sourceData[a].jjxId][b].jjConfig[c].jjxId)) {
              //生成list数据
              fpsjList.set(this.sourceData[a].jjxId + "-" + this.sourceDataSub[this.sourceData[a].jjxId][b].jjConfig[c].jjxId, {
                zjjxId: this.sourceData[a].jjxId,
                zjjxMc: this.sourceData[a].jjxName,
                jjxId: this.sourceDataSub[this.sourceData[a].jjxId][b].jjConfig[c].jjxId,
                jjxMc: this.sourceDataSub[this.sourceData[a].jjxId][b].jjConfig[c].jjxName
              });

              this.$set(
                fpsjList.get(this.sourceData[a].jjxId + "-" + this.sourceDataSub[this.sourceData[a].jjxId][b].jjConfig[c].jjxId),
                this.sourceDataSub[this.sourceData[a].jjxId][b].fzName,
                this.sourceDataSub[this.sourceData[a].jjxId][b].jjConfig[c].jjJe
              );
            } else {
              //生成list数据
              var jjje = fpsjList.get(this.sourceData[a].jjxId + "-" + this.sourceDataSub[this.sourceData[a].jjxId][b].jjConfig[c].jjxId)[this.sourceDataSub[this.sourceData[a].jjxId][b].fzName];
              this.$set(
                fpsjList.get(this.sourceData[a].jjxId + "-" + this.sourceDataSub[this.sourceData[a].jjxId][b].jjConfig[c].jjxId),
                this.sourceDataSub[this.sourceData[a].jjxId][b].fzName,
                (jjje == undefined ? 0 : jjje) + this.sourceDataSub[this.sourceData[a].jjxId][b].jjConfig[c].jjJe
              );
            }
          }
        }
      }

      this.fpsjList = [...fpsjList.values()];
      this.lieList = [...lieList.values()];

      this.drawer = true;
      setTimeout(() => {
        this.tablebz = true;
      }, 500);
    },
    dataFormSubmit() {
      this.setError1();
      if (this.submitError()) {
        return;
      }

      this.setError2();
      if (this.submitError()) {
        return;
      }

      if (this.fpData.sfCeff != '是') {
        for (var a in this.sourceData) {
          if (this.sourceMap[this.sourceData[a].jjxId].jjYe < 0) {
            this.$notify.closeAll();
            this.$notify.error("金额已超上限【奖金项：" + this.sourceData[a].jjxName + "】");
            return;
          }
        }
      }

      this.fpData.bmJj = this.pzHjs;
      this.fpData.jjYe = this.jjye - this.pzHjs;
      this.fpData.jjxJeXq = JSON.stringify(this.sourceMap);

      this.fpData.bmFpfs = "公式";
      this.fpData.bmGs = JSON.stringify(this.sourceDataSub);

      const loading = this.$loading({
        lock: true,
        text: `正在计算中,请稍后......`,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      updateBm(this.fpData).then(data => {
        this.dataList = data.data.data;
       //console.log("this.dataList:"+JSON.stringify(this.dataList))
        this.dataProcessing();

        //人工、公式加入重置
        this.setDataListJjZeY();
        this.setDataColumns();

        this.value = true;
        this.cutPage = false;
        loading.close()
      }).catch(() => {
        loading.close()
      });
    },
    saveBmList() {
      // for (var a in this.dataList) {
      //   if (this.dataList[a].jjJe != this.dataList[a].jjYsje && this.dataList[a].jjBz == null) {
      //     this.$notify.closeAll();
      //     this.$notify.error("未输入修改备注【" + this.dataList[a].deptName + "：" + this.dataList[a].jjxMc + "】");
      //     return;
      //   }
      // }
      if (this.fpData.sfCeff != '是') {
        for (var a in this.sourceData) {
          if ((this.calculationMap[this.sourceData[a].jjxId].jje - this.calculationMap[this.sourceData[a].jjxId].sye) < 0) {
            this.$notify.closeAll();
            this.$notify.error("金额已超上限【奖金项：" + this.sourceData[a].jjxName + "】");
            return;
          }
        }
      }

      if (this.dataList.length > 0) {
        saveBmList(this.dataList).then(data => {
          if (this.value) {
            this.fpData.bmFpfs = "公式";
          } else {
            this.fpData.bmFpfs = "人工";
          }

          //金额计算
          this.fpData.bmJj = this.lbHjs;
          this.fpData.jjYe = this.jjye - this.lbHjs;

          putObj(this.fpData).then(res => {
            this.$notify.closeAll();
            this.$notify.success("保存成功");
            this.callback();
          }).catch(() => {
            this.$notify.error("数据错误")
          });
        }).catch(() => {
        });
      } else {
        this.$notify.closeAll();
        this.$notify.error("没有相关操作数据")
      }
    },
    //取得奖金项名称
    getJJxName(key) {
      let lResult = "";
      this.jjxOptions.find(u => {
        if (u.id === key) {
          lResult = u.jjxMc;
        }
      })
      return lResult;
    },
    //取得奖金项日期
    getJJxDate(key) {
      let jjxOptions = JSON.parse(this.fpData.jjxXq);
      let lResult = "";
      jjxOptions.find(u => {
        if (u.jjxId === key) {
          lResult = u.jjxDate;
        }
      })
      return lResult;
    },
    //取得公式名称
    getGsMc(key) {
      let lResult = "";
      this.gsData.find(u => {
        if (u.id === key) {
          lResult = u.gsMc;
        }
      })
      return lResult;
    },
    btnDel(value, indexD, indexX) {
      this.sourceDataSub[this.sourceData[indexD].jjxId].splice(indexX, 1);
      this.pzChange();
    },
    btnDel3(e, indexD, indexX, index3) {
      e.stopPropagation();
      this.sourceDataSub[this.sourceData[indexD].jjxId][indexX].jjConfig.splice(index3, 1);

      if (this.sourceDataSub[this.sourceData[indexD].jjxId][indexX].jjConfig.length == 0) {
        this.sourceDataSub[this.sourceData[indexD].jjxId].splice(indexX, 1);
      }

      this.pzChange();
    },
    elJjxChange(value, indexD, indexX, index3) {
      const lId = this.sourceData[indexD].jjxId;
      this.$set(this.sourceDataSub[lId][indexX]["jjConfig"][index3], "jjxName",
        this.getJJxName(this.sourceDataSub[lId][indexX]["jjConfig"][index3].jjxId));
    },
    elGsChange(value, indexD, indexX, index3) {
      const lId = this.sourceData[indexD].jjxId;
      this.$set(this.sourceDataSub[lId][indexX]["jjConfig"][index3], "gsName",
        this.getGsMc(this.sourceDataSub[lId][indexX]["jjConfig"][index3].gsId));
    },
    //加3级菜单
    btnAddItem(value, indexD, indexX) {
      let lId = 0;
      lId = this.sourceData[indexD].jjxId;
      let fzInfo = [];
      for (var x in this.fzMx) {
        if (this.fzMx[x].fzId == this.sourceDataSub[lId][indexX].fzId) {
          fzInfo.push({
            deptCode: this.fzMx[x].jgDeptCode,
            deptName: this.fzMx[x].jgDeptName,
            jjJe: 0
          })
        }
      }

      this.sourceDataSub[lId][indexX].jjConfig.push({
        gsId: '',
        gsName: "",
        jjJe: 0,
        jjxId: lId,
        jjxName: this.getJJxName(lId),
        jjxDate: this.getJJxDate(lId),
        fzInfo: fzInfo,
        errMsg: ''
      })

    },
    setError1() {
      let sStr = [];
      sStr = Object.keys(this.sourceDataSub);

      for (let i = 0; i < sStr.length; i++) {
        for (let j = 0; j < this.sourceDataSub[sStr[i]].length; j++) {
          for (let k = 0; k < this.sourceDataSub[sStr[i]][j]["jjConfig"].length; k++) {
            this.sourceDataSub[sStr[i]][j]["jjConfig"][k].errMsg = "";
            if (this.sourceDataSub[sStr[i]][j]["jjConfig"][k].jjxId === "") {
              this.sourceDataSub[sStr[i]][j]["jjConfig"][k].errMsg = "奖金项未选择";
              continue;
            }
            if (this.sourceDataSub[sStr[i]][j]["jjConfig"][k].gsId === "") {
              this.sourceDataSub[sStr[i]][j]["jjConfig"][k].errMsg = "公式未选择";
              continue;
            }
            if (this.sourceDataSub[sStr[i]][j]["jjConfig"][k].jjxDate === "" ||
              this.sourceDataSub[sStr[i]][j]["jjConfig"][k].jjxDate == null) {
              this.sourceDataSub[sStr[i]][j]["jjConfig"][k].errMsg = "日期未选择";
              continue;
            }
            if (this.sourceDataSub[sStr[i]][j]["jjConfig"][k].jjJe === "" ||
              this.sourceDataSub[sStr[i]][j]["jjConfig"][k].jjJe == null) {
              this.sourceDataSub[sStr[i]][j]["jjConfig"][k].errMsg = "金额未输入";
              continue;
            }
          }
        }
      }
    },
    //错误提示
    submitError() {
      let lErr = false;
      let sStr = [];
      sStr = Object.keys(this.sourceDataSub);

      for (let i = 0; i < sStr.length; i++) {
        if (lErr) break;
        for (let j = 0; j < this.sourceDataSub[sStr[i]].length; j++) {
          lErr = this.submitErrorInner(this.sourceDataSub[sStr[i]][j]);
          if (lErr) break;
        }
      }
      return lErr;
    },
    //不修改原验证逻辑，添加
    submitErrorInner(sourceDataSub3) {
      for (let k = 0; k < sourceDataSub3["jjConfig"].length; k++) {
        if (sourceDataSub3["jjConfig"][k].errMsg !== "") {
          return true;
        }
      }
      return false;
    },
    setError2() {
      if (this.sourceData.length < 2) {
        return;
      }

      // 1.比较
      let l1 = this.sourceData.length - 1;
      let strComparesn = [];
      let llId = '';
      let swich = false;


      for (let a = 1; a <= l1; a++) {
        strComparesn = [];
        llId = '';
        if (swich) break;

        llId = this.sourceData[a].jjxId;
        strComparesn = this.getComparesJjxId(this.getComparesIndex(a));

        // 调试用
        for (let b = 0; b < this.sourceDataSub[llId].length; b++) {
          if (swich) break;
          for (let c = 0; c < this.sourceDataSub[llId][b]["jjConfig"].length; c++) {
            this.sourceDataSub[llId][b]["jjConfig"][c].errMsg = "";

            if (strComparesn.indexOf(this.sourceDataSub[llId][b]["jjConfig"][c].jjxId) > -1) {
              this.sourceDataSub[llId][b]["jjConfig"][c].errMsg = "【" + this.sourceDataSub[llId][b]["jjConfig"][c].jjxName + "】已存在于";
              this.sourceDataSub[llId][b]["jjConfig"][c].errMsg += this.showMessages(this.sourceDataSub[llId][b]["jjConfig"][c].jjxId);
              swich = true;
              break;
            }
          }
        }
      }
    },
    //最后详细说明
    showMessages(jjxId) {
      let lResult = "";
      let bSwich = false;
      let lId = "";

      for (let i = 0; i < this.sourceData.length; i++) {
        lId = "";
        lId = this.sourceData[i].jjxId;
        if (bSwich) break;
        for (let j = 0; j < this.sourceDataSub[lId].length; j++) {
          if (bSwich) break;
          for (let k = 0; k < this.sourceDataSub[lId][j]["jjConfig"].length; k++) {
            if (this.sourceDataSub[lId][j]["jjConfig"][k].jjxId === jjxId) {
              lResult = "序号：" + (i + 1) + "【" + this.sourceData[i].jjxName + "】"
              lResult += "_" + (j + 1) + "【" + this.sourceDataSub[lId][j].fzName + "】";
              lResult += "_" + (k + 1) + "中";
              bSwich = true;
              break;
            }
          }

        }
      }
      return lResult;
    },

    //取得比较数据1
    getComparesIndex(l1) {
      let sStr = [];
      for (let i = 0; i < l1; i++) {
        // sStr.push(this.sourceData[i].jjxId+'_'+this.sourceData[i].jjxName)
        sStr.push(this.sourceData[i].jjxId)
      }
      return sStr;
      // return sStr.join(',');
    },
    //取得比较数据2
    getComparesJjxId(str) {
      let l1 = [];
      let l2 = [];

      for (let i = 0; i < str.length; i++) {
        for (let j = 0; j < this.sourceDataSub[str[i]].length; j++) {
          for (let k = 0; k < this.sourceDataSub[str[i]][j]["jjConfig"].length; k++) {
            l1.push(this.sourceDataSub[str[i]][j]["jjConfig"][k].jjxId)
          }
        }
      }

      //去重
      l2 = [...new Set(l1)];
      return l2;
    },

    //拼接横板显示
    setDataColumns(){
      const loading = this.$loading({
        lock: true,
        text: `正在获取数据,请稍后......`,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.tableJjxMc = [];
      this.tableResult = [];
      let tableName = [];

      // 机构名称
      tableName = this.getNoneReport(this.dataList,"deptName");
      ////console.log(tableName);

      // 奖金项名称
      const jjxMc = this.getNoneReport(this.dataList,"jjxMc");
      this.tableJjxMc = jjxMc;
      ////console.log(jjxMc);

      //拼数据
      for(let i=0;i<tableName.length;i++){
         var jjPnum = 0;
	     for(let m = 0; m < this.dataList.length; m++){
            if(this.dataList[m]["deptName"] === tableName[i]){
              jjPnum = this.dataList[m]["deptPnum"];
              break;
            }
          }
        // 机构数组，取奖金总额用
        const Dljg = this.getDljg(this.dataList,tableName[i]);
        ////console.log(Dljg);

        //奖金总额分类
        const ZlJjze = this.getNoneReport(Dljg,"jjZey")
        ////console.log(ZlJjze);

        //竖拼接横
        for(let j=0;j<ZlJjze.length;j++){
          let cObj = {}

          for(let k=0;k<jjxMc.length;k++){
            const kX= jjxMc[k];

            if (k===0){
              cObj = {};
              cObj["deptId"] = null ;
              cObj["deptName"] =tableName[i];
              cObj["jjZey"] =ZlJjze[j];
              cObj["jjPnum"] = jjPnum?jjPnum:0;
              cObj["jjPavg"] = cObj["jjPnum"]==0?0:(parseFloat(ZlJjze[j]) / jjPnum).toFixed(2);
            }

            this.$set(cObj,kX,null);
            this.$set(cObj,kX+"备注", null);
            this.$set(cObj,kX+'value','');
            this.$set(cObj,kX+"备注value","");
            // this.$set(cObj,kX,kX);
            // cObj[kX] =kX;

            if(k === jjxMc.length -1) this.tableResult.push(cObj);
          }
        }
      }

      let lIndex = -1;
      //给拼接得新数据赋值
      for(let i=0;i<this.tableResult.length;i++){
        for(let j=0;j<jjxMc.length;j++){
           var je = 0;
          for(let m = 0; m < this.dataList.length; m++){
            if(this.dataList[m]["deptName"] === this.tableResult[i]["deptName"] && 
              this.dataList[m]["jjxMc"] === jjxMc[j]){
              je = je + this.dataList[m]["jjJe"]
            }
          }
          lIndex = -1;
          lIndex = this.getColumnIndex(this.tableResult[i]["deptName"],this.tableResult[i]["jjZey"],jjxMc[j]);

          ////console.log(this.tableResult[i]["deptName"]+" >> " + this.tableResult[i]["jjZey"] + " >> " +jjxMc[j] + "  >> " +lTemp)
         // this.$set(this.tableResult[i],jjxMc[j]+'value',this.dataList[lIndex]["jjJe"]);
           this.$set(this.tableResult[i],jjxMc[j]+'value',je.toFixed(2));
          this.tableResult[i][jjxMc[j]] = this.dataList[lIndex];
        
          if(this.dataList[lIndex]){
             this.$set(this.tableResult[i],jjxMc[j]+"备注value",this.dataList[lIndex]["jjBz"]);
              this.tableResult[i][jjxMc[j]+"备注"] = this.dataList[lIndex];

          this.tableResult[i]["deptId"] = this.dataList[lIndex].deptId;
          }
         
         
        }
      }
      loading.close()
      ////console.log(this.dataList);
      ////console.log(this.tableResult);

    },
    //取得数组索引
    getColumnIndex(cJgmc,cJjze,cJjxMc){
      let lIndex = -1;

      for(let i=0;i<this.dataList.length;i++){
        if(this.dataList[i]["deptName"] === cJgmc && this.dataList[i]["jjZey"] == cJjze
          && this.dataList[i]["jjxMc"] === cJjxMc){
          lIndex = i;
          break;
        }
      }

      return lIndex;
    },
    // 取得机构 大类1
    getDljg(arr,key){
      let lResult = [];
      arr.map(u=>{
        if(u.deptName === key){
          lResult.push(u);
        }
      })
      return lResult;
    },

    //取重复
    getNoneReport(arr,key){
      let lResult = [];
      let lResultObj = {};
      let group = '';

      for(let i=0;i<arr.length;i++){
        group = '';
        group = JSON.parse(JSON.stringify(arr[i][key]));
        lResultObj[group] = lResultObj[group] || '';
      }
      Object.keys(lResultObj).map(u=>{
        lResult.push(u);
      })
      return lResult;
    },

    //导出
    btnExportJg(){
      const excelName = '部门分配详情表';
      const ref = 'bmxqTable';

      try {
        const $e = this.$refs[ref].$el
        let $table = $e.querySelector('.el-table__fixed')
        if (!$table) {
          $table = $e
        }
        const wb = XLSX.utils.table_to_book($table, {
          raw: true
        })

        const wbout = XLSX.write(wb, {
          bookType: 'xlsx',
          bookSST: true,
          type: 'array'
        })
        FileSaver.saveAs(
          new Blob([wbout], {
            type: 'application/octet-stream'
          }),
          `${excelName}.xlsx`,
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.error(e)
      }


    },

  }
}
</script>
<style scoped lang="scss">
.el-tooltip__popper.is-light {
  width: 1000px !important;
  left: 0 !important;
}
.fangwen{
  background: linear-gradient(-100deg, #0093e9, #173198);width: 90%;
  color: #fff;padding: 10px 20px;border-radius: 5px; height: 36px; line-height: 36px; font-size: 14px;cursor:pointer;
}
</style>
